package org.fast.framework.container;

import org.fast.framework.util.ReflectionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * <p>Bean 容器
 * 存放class与实例的映射关系，获取某个bean实例等</p>
 */
public final class BeanContainer {

    private static final Logger LOGGER = LoggerFactory.getLogger(BeanContainer.class);

    // 存放Bean类与Bean实例的映射关系
    private static final Map<Class<?>, Object> BEAN_MAP = new HashMap<>();

    static {
        Set<Class<?>> beanClassSet = ClassContainer.getBeanClassSet();
        for (Class<?> beanClass : beanClassSet) {
            Object obj = ReflectionUtil.newInstance(beanClass);
            BEAN_MAP.put(beanClass, obj);
            LOGGER.info("loaded bean " + beanClass.getName());
        }
    }

    /**
     * 获取Bean映射
     *
     * @return
     */
    public static Map<Class<?>, Object> getBeanMap() {
        return BEAN_MAP;
    }

    /**
     * 获取Bean实例
     *
     * @param clazz 类
     * @param <T>   实例
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        if (!BEAN_MAP.containsKey(clazz)) {
            throw new RuntimeException("can not get bean by class: " + clazz);
        }
        return (T) BEAN_MAP.get(clazz);
    }

    /**
     * 设置bean实例
     *
     * @param clazz 类
     * @param obj   实例
     */
    public static void setBean(Class<?> clazz, Object obj) {
        BEAN_MAP.put(clazz, obj);
    }
}
